<?php

namespace iflow\swoole\implement\Server\Http;

use iflow\Container\Container;
use iflow\swoole\abstracts\ServicesAbstract;
use iflow\swoole\implement\Server\Http\Event\Event;
use iflow\swoole\implement\Server\WebSocket\WebSocket;
use Swoole\Http\Server;

class Service extends ServicesAbstract {

    protected array $events = [
        'request' => 'onRequest',
        'task'    => 'onTask',
        'finish'  => 'onFinish'
    ];

    protected bool $isWebSocket = false;

    protected string $defaultEventClass = Event::class;

    public function start() {
        parent::start(); // TODO: Change the autogenerated stub

        if ($this->isWebSocket) {
            $this -> registerWebSocketService();
        }

        $event = Container::getInstance() -> make($this->getEventClass('aliasEvent'), [ $this ]);
        $this->events = $event -> getEvent($this -> events);

        $this -> registerSwServiceEvent($this) -> printStartContextToConsole(
            $this->isWebSocket ? [ 'http', 'ws' ] : 'http'
        );

        $this->SwService -> start();
    }

    public function onRequest(object $request, object $response): mixed {
        return event('RequestVerification', $request, $response, microtime(true));
    }

    protected function getSwooleServiceClass(): string {
        return Server::class;
    }

    protected function registerWebSocketService(): Service {
        // TODO: 注册 WebSocket 服务
        Container::getInstance() -> make(WebSocket::class, [ $this->servicesCommand -> config -> get('websocket'), $this ], true);
        return $this;
    }

}